package utils

import (
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/websocket"
	"github.com/kataras/neffos"
	"github.com/spf13/cast"
	"time"
	"wit-admin-go/conf"
	"wit-admin-go/system/app/dto"
	log "wit-admin-go/system/zaplogger"
)

// 值也应该与客户端匹配。
// const enableJWT = true
const namespace = "default"

type WitWebSocket struct {
	Ws *neffos.Server
	//map的value存储id，用于区分用户
	Connect map[*neffos.Conn]string
}

func NewSocket() *WitWebSocket {
	Ws := WitWebSocket{
		Connect: make(map[*neffos.Conn]string),
	}
	return &Ws
}

// SetUID 设置用户信息
func (w *WitWebSocket) SetUID(con *neffos.Conn, id string) {
	witWebSocket.Connect[con] = id
}

// DelConn 移除连接
func (w *WitWebSocket) DelConn(c *neffos.Conn) {
	delete(w.Connect, c)
}

var witWebSocket *WitWebSocket

func InitWebSocket(app *iris.Application) {
	witWebSocket = NewSocket()
	witWebSocket.Handle(app, conf.CONFIG.WitAdmin.WebSocketPath)
	go func() {
		//推送消息
		defer func() {
			if err := recover(); err != nil {
				log.Log.Errorf("recover:%v", err)
			}
		}()
		time.Sleep(1 * time.Minute)
		SendUser("88bea40ee47d4a52ba06cdf646cb8155", "aaaaaaaaa")
	}()
}

func (w *WitWebSocket) Handle(app *iris.Application, path string) {
	witWebSocket.Ws = websocket.New(websocket.DefaultGobwasUpgrader, websocket.Events{
		websocket.OnNativeMessage: func(nsConn *websocket.NSConn, msg websocket.Message) error {
			log.Log.Infof("[WebSocket消息]:当前在线%d人 %s 来自 [%s]", len(w.Connect), msg.Body, nsConn.Conn.ID())
			return nil
		},
	})
	//连接时设置用户信息
	witWebSocket.Ws.OnConnect = func(c *websocket.Conn) error {
		log.Log.Infof("[WebSocket消息] 当前在线%d人 用户 [%s] 连接成功！", len(w.Connect)+1, c.ID())
		ctx := websocket.GetContext(c)
		id := ctx.URLParam("id")
		log.Log.Warn(id)
		witWebSocket.SetUID(c, id)
		return nil
	}
	witWebSocket.Ws.OnDisconnect = func(c *websocket.Conn) {
		witWebSocket.DelConn(c)
		log.Log.Infof("[WebSocket消息] 用户 [%s] 断开连接！", c.ID())
	}
	witWebSocket.Ws.OnUpgradeError = func(err error) {
		log.Log.Errorf("WebSocket连接失败: %v", err)
	}
	app.Get(path, websocket.Handler(witWebSocket.Ws))
}

// SendUser 给指定用户发送消息
func SendUser(id string, data interface{}) {
	cons := witWebSocket.Connect
	for con, u := range cons {
		if u == id {
			isSuc := con.Write(websocket.Message{
				To:   id,
				Body: []byte(cast.ToString(dto.Result{Code: 200, Data: data, Msg: "ok"})),
			})
			if isSuc {
				log.Log.Info(id, "成功")
			}
		}
	}
}

/*
群发本质上就是给多条连接推送信息
*/
